<template>
  <view class="container">
    <!-- 横向滚动菜单 -->
	
    <scroll-view 
      class="menu-scroll" 
      scroll-x 
      :scroll-into-view="'tab-' + currentIndex"
      :show-scrollbar="false"
      :scroll-with-animation="true"
    >
	
      <view class="menu-items">
        <view 
          v-for="(item, index) in treeData" 
          :key="index"
          :id="'tab-' + index"
		  class="menu-item active" 
         
          @click="handleMenuClick(index)"
        >
		 <!-- :class="['menu-item', currentIndex === index ? 'active' : '']" -->
          <text class="item-text">{{ item.categoryname }}</text>
          <!-- 添加选中指示器 -->
          <!-- <view v-if="currentIndex === index" class="active-indicator"></view> -->
        </view>
      </view>
    </scroll-view>

    <!-- 内容区域 -->
    <scroll-view 
      class="content-scroll"
      scroll-y
      :scroll-into-view="'content-' + currentIndex"
      :scroll-with-animation="true"
      :style="{height: contentHeight + 'px'}"
      @scroll="handleContentScroll"
    >
      <view 
        v-for="(item, index) in treeData" 
        :key="index"
        :id="'content-' + index"
        class="section"
      >
	 
        <view class="section-title">{{item.categoryname}}</view>
        <view>
          <view v-for="(itChidren, cIndex) in item.chapters" :key="cIndex">
            <text class="tech-name stageName">{{ itChidren.chapterName }}</text>
            <view class="tech-grid">
              <view 
                v-for="(itCh, courseIndex) in itChidren.courses" 
                :key="courseIndex" 
                class="tech-item"
              >
                <view @click="add(itCh)" @tap="toClass(itCh)" class="item">
                  <img class="tech-icon" :src="itCh.courseImgsrc" draggable="false">
                  <text class="courseName">{{ itCh.courseName }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部导航 -->
<!--    <view class="tab-bar">
      <view 
        v-for="(item, index) in tabItems" 
        :key="index" 
        class="tab-item"
        @click="handleTabClick(index)"
      >
        <text :class="['tab-text', currentTab === index ? 'active' : '']">
          {{ item.name }}
        </text>
      </view>
    </view> -->
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted ,onUnmounted} from 'vue';
import { getClazzCenter } from '@/pages/utils/api/clazz.js'
import { addCount } from '@/pages/utils/api/clazz.js';

const currentIndex = ref(0);
const currentTab = ref(0);
const contentHeight = ref(0);
const treeData = ref<any[]>([]);
const menuScrollRef = ref(null);
const lastScrollTime = ref(0); // 防止滚动事件冲突

const tabItems = [
  { name: '首页', icon: 'home' },
  { name: '发现', icon: 'search' },
  { name: '学习', icon: 'bookmark' },
  { name: '我的', icon: 'person' }
];

// 计算内容区域高度
const calculateHeight = () => {
  const systemInfo = uni.getSystemInfoSync();
  const windowHeight = systemInfo.windowHeight;
  const query = uni.createSelectorQuery();
  query.select('.menu-scroll').boundingClientRect();
  query.select('.tab-bar').boundingClientRect();
  query.exec(res => {
    const menuHeight = res[0]?.height || 50; // 默认高度50px
    const tabBarHeight = res[1]?.height || 80; // 默认高度80px
    contentHeight.value = windowHeight - menuHeight - tabBarHeight;
  });
};

// 内容区域滚动处理
const handleContentScroll = (event) => {
  const now = Date.now();
  // 防止滚动事件冲突
  if (now - lastScrollTime.value < 300) return;
  lastScrollTime.value = now;
  
  // 计算当前滚动位置对应的索引
  const scrollTop = event.detail.scrollTop;
  const query = uni.createSelectorQuery();
  let found = false;
  
  treeData.value.forEach((item, index) => {
    if (found) return;
    query.select(`#content-${index}`).boundingClientRect();
  });
  
  query.exec(res => {
    if (!res) return;
    
    for (let i = res.length - 1; i >= 0; i--) {
      const rect = res[i];
      if (rect && rect.top <= 100) {
        // 添加防抖和边界条件
        if (Math.abs(currentIndex.value - i) > 0) {
          currentIndex.value = i;
          lastScrollTime.value = now;
        }
        found = true;
        break;
      }
    }
  });
};

const fetchData = async () => {
  try {
    const res = await getClazzCenter();
    treeData.value = buildCourseTree(res.data);

	console.log( treeData.value,"树形结构")
  } catch (error) {
    console.error('获取数据失败', error);
  }
};

function toClass(item) {
  uni.navigateTo({
    url: `/pages/clazz/index?courseId=${item.courseId}&courseName=${item.courseName}&description=${item.description}`,
    fail: (err) => {
      uni.showToast({
        title: '跳转失败: ' + err.errMsg,
        icon: 'none'
      });
    }
  });
}

const handleMenuClick = (index) => {
  currentIndex.value = index;
  lastScrollTime.value = Date.now();
  
  // 确保内容区域滚动到正确位置
  nextTick(() => {
    uni.pageScrollTo?.({
      selector: `#content-${index}`,
      duration: 300,
      complete: () => lastScrollTime.value = 0
    });
  });
};

const handleTabClick = (index) => {
  currentTab.value = index;
  // 添加导航切换逻辑...
};

const add = (item) => {
  const courseId = Number(item.courseId);
  addCount(courseId);
};

function buildCourseTree(data) {
  const categoryMap = new Map();

  data.forEach(item => {
    const categoryName = item.categoryname;
    if (!categoryName) return;

    if (!categoryMap.has(categoryName)) {
      categoryMap.set(categoryName, {
        categoryId: item.parentCategoryId || item.categoryId,
        categoryname: categoryName,
        chapters: new Map()
      });
    }
    const category = categoryMap.get(categoryName);

    const chapterName = item.chapterNames;
    if (!category.chapters.has(chapterName)) {
      category.chapters.set(chapterName, {
        chapterName: chapterName,
        courses: []
      });
    }
    const chapter = category.chapters.get(chapterName);

    chapter.courses.push({
      courseName: item.courseName,
      price: item.price,
      categoryId: item.categoryId,
      courseImgsrc: item.courseImgsrc,
      description: item.description,
      courseId: item.courseId,
    });
  });

  return Array.from(categoryMap.values()).map(category => ({
    ...category,
    chapters: Array.from(category.chapters.values())
  }));
}

onMounted(() => {
  calculateHeight();
  fetchData();
  
  // // 添加窗口大小变化的监听
  // window.addEventListener('resize', calculateHeight);
  // uni.onWindowResize(() => {
  //   calculateHeight();
  // });
  
  // 组件卸载时清除监听
  onUnmounted(() => {
    window.removeEventListener('resize', calculateHeight);
  });
});
</script>

<style scoped>
page {
  height: 100%;
  box-sizing: border-box;
}

.container {
  min-height: 100%;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  padding-bottom: 80rpx; /* 底部导航高度 */
}

.menu-scroll {
  width: 100%;
  white-space: nowrap;
  background-color: #fff;
  padding: 10px 0;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}

.menu-items {
  display: inline-flex;
  padding: 0 10px;
  gap: 20px;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px 15px;
  border-radius: 16px;
  transition: all 0.3s ease;
}

.menu-item.active {
  background-color: #007AFF;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,122,255,0.2);
}

.item-text {
  font-size: 14px;
  color: #666;
  transition: all 0.3s ease;
  font-weight: 500;
}

.menu-item.active .item-text {
  color: #fff;
  font-weight: 600;
}

/* 选中指示器 */
.active-indicator {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #fff;
  margin-top: 5px;
}

.content-scroll {
  flex: 1;
  background-color: #f5f5f5;
  padding-top: 15px;
}

.section {
  background-color: #fff;
  padding: 25rpx 30rpx;
  margin-bottom: 20rpx;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  padding-bottom: 15rpx;
  border-bottom: 1px solid #eee;
}

.tech-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 25rpx;
}

.tech-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
}

.tech-icon {
  width: 130rpx;
  height: 130rpx;
  border-radius: 16rpx;
  background: #f9f9f9;
  object-fit: cover;
  border: 1px solid #f0f0f0;
}

.courseName {
  font-size: 22rpx;
  margin-top: 15rpx;
  color: #333;
  text-align: center;
  line-height: 1.4;
}

.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  justify-content: space-around;
  align-items: center;
  border-top: 1px solid #eee;
  z-index: 100;
  padding-bottom: env(safe-area-inset-bottom);
}

.tab-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10rpx;
}

.tab-text {
  font-size: 24rpx;
  color: #999;
  transition: color 0.3s;
}

.tab-text.active {
  color: #007AFF;
  font-weight: 600;
  position: relative;
}

/* 添加导航激活指示器 */
.tab-text.active::after {
  content: "";
  position: absolute;
  width: 8px;
  height: 8px;
  background-color: #007AFF;
  border-radius: 50%;
  top: -10px;
}
</style>